<!DOCTYPE html>
<html>

<head>
    <title>Welcome</title>
    <!-- 引入jQuery和Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        #userListContainer {
            min-height: 400px;
            position: relative;
            margin-bottom: 70px;
            /* 为分页控件留出空间 */
        }

        .table-responsive {
            max-height: 500px;
            overflow-y: auto;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
            border-radius: 4px;
        }

        .table {
            margin-bottom: 0;
        }

        .table thead {
            position: sticky;
            top: 0;
            background-color: #f8f9fa;
            z-index: 10;
        }

        .pagination-footer {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px 0;
            background-color: #fff;
            border-top: 1px solid #dee2e6;
            box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05);
        }

        .pagination-container {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .page-info {
            margin: 0 15px;
            line-height: 1.5;
        }

        /* 空数据提示样式 */
        .empty-data {
            text-align: center;
            padding: 50px 0;
            color: #6c757d;
        }

        /* 表格行高优化 */
        .table tbody tr {
            height: 45px;
        }

        /* 表头样式优化 */
        .table thead th {
            padding: 12px 8px;
            vertical-align: middle;
        }

        /* 表格单元格样式优化 */
        .table tbody td {
            padding: 8px;
            vertical-align: middle;
        }

        /* 加载状态 */
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .loading-spinner.active {
            display: block;
        }
    </style>
</head>

<body>
    <div class="container mt-4">
        <h1>Hello, {{ name }}!</h1>
        <button id="addBtn" class="btn btn-primary mb-3">添加数据</button>

        <!-- 用户列表部分 -->
        <div id="userListContainer">
            <div class="loading-spinner">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">正在加载数据...</p>
            </div>

            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>姓名</th>
                            <th>邮箱</th>
                            <th>创建时间</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody">
                        <!-- 数据将通过JS动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-footer">
            <div class="container">
                <div class="pagination-container">
                    <nav aria-label="Page navigation">
                        <ul class="pagination mb-0" id="paginationContainer">
                            <!-- 分页按钮将通过JS动态加载 -->
                        </ul>
                    </nav>
                    <div class="page-info" id="pageInfo"></div>
                </div>
            </div>
        </div>

        <!-- Bootstrap弹框 -->
        <div class="modal fade" id="dataModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">添加数据</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="dataForm" novalidate>
                            <div class="mb-3">
                                <label for="name" class="form-label">姓名</label>
                                <input type="text" class="form-control" id="name" name="name" placeholder="姓名" required>
                                <div class="invalid-feedback">请输入姓名</div>
                            </div>
                            <div class="mb-3">
                                <label for="email" class="form-label">邮箱</label>
                                <input type="email" class="form-control" id="email" name="email" placeholder="邮箱"
                                    required>
                                <div class="invalid-feedback">请输入有效的邮箱地址</div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button id="submitBtn" class="btn btn-success">提交</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 当前分页状态
        let currentPage = 1;
        const perPage = 10; // 与后端默认值保持一致

        $(document).ready(function () {
            // 页面加载时获取用户数据
            refreshUserList(currentPage);

            $("#addBtn").click(function () {
                $("#dataModal").modal("show");
            });

            // 表单提交处理
            $('#submitBtn').click(function () {
                // 表单验证
                // if (!validateForm()) {
                //     return;
                // }

                $.ajax({
                    url: '/user',
                    method: 'POST',
                    data: $('#dataForm').serialize(),
                    beforeSend: function () {
                        $('#submitBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 提交中...');
                    },
                    success: function (response) {
                        $('#dataModal').modal('hide');
                        $('#dataForm')[0].reset();
                        refreshUserList(1); // 提交后回到第一页
                        showAlert('提交成功', 'success');
                    },
                    error: function (xhr) {
                        showAlert('提交失败: ' + xhr.statusText, 'danger');
                    },
                    complete: function () {
                        $('#submitBtn').prop('disabled', false).text('提交');
                    }
                });
            });

            // 分页按钮事件委托
            $(document).on('click', '.page-btn', function (e) {
                e.preventDefault();
                const page = $(this).data('page');
                if (page !== currentPage) {
                    currentPage = page;
                    refreshUserList(currentPage);
                }
            });

            // 表单输入时清除验证状态
            $('#dataForm input').on('input', function () {
                $(this).removeClass('is-invalid');
                $(this).next('.invalid-feedback').hide();
            });
        });

        // 表单验证
        function validateForm() {
            let isValid = true;

            // 验证姓名
            const nameInput = $('#name');
            if (!nameInput.val().trim()) {
                nameInput.addClass('is-invalid');
                nameInput.next('.invalid-feedback').show();
                isValid = false;
            }

            // 验证邮箱
            const emailInput = $('#email');
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailInput.val() || !emailRegex.test(emailInput.val())) {
                emailInput.addClass('is-invalid');
                emailInput.next('.invalid-feedback').show();
                isValid = false;
            }

            return isValid;
        }

        // 显示提示消息
        function showAlert(message, type) {
            const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;

            // 移除旧的提示
            $('.alert').alert('close');

            // 添加新提示
            $('.container').prepend(alertHtml);

            // 5秒后自动消失
            setTimeout(() => {
                $('.alert').alert('close');
            }, 5000);
        }

        // 刷新用户列表的函数（带分页）
        function refreshUserList(page = 1) {
            $('.loading-spinner').addClass('active');
            $('#userTableBody').empty();

            $.get(`/user?page=${page}&per_page=${perPage}`, function (data) {
                // 渲染用户列表
                let html = '';

                if (data.users && data.users.length > 0) {
                    data.users.forEach(user => {
                        const createdAt = user.create_time ?
                            new Date(user.create_time).toLocaleString('zh-CN', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit'
                            }) : '';

                        html += `<tr>
                    <td>${user.id}</td>
                    <td>${user.name}</td>
                    <td>${user.email}</td>
                    <td>${createdAt}</td>
                </tr>`;
                    });
                } else {
                    html = `<tr><td colspan="4" class="empty-data">暂无数据</td></tr>`;
                }

                $('#userTableBody').html(html);

                // 更新分页控件
                updatePagination(data.pagination);

            }).fail(function (xhr) {
                console.error("获取用户列表失败: ", xhr.statusText);
                $('#userTableBody').html(`<tr><td colspan="4" class="empty-data">数据加载失败</td></tr>`);
            }).always(function () {
                $('.loading-spinner').removeClass('active');
            });
        }

        // 更新分页控件
        function updatePagination(pagination) {
            let paginationHtml = '';

            // 只有多于1页时才显示分页控件
            if (pagination.pages > 1) {
                paginationHtml = `
            <li class="page-item ${pagination.has_prev ? '' : 'disabled'}">
                <a class="page-link page-btn" href="#" data-page="${pagination.current_page - 1}">上一页</a>
            </li>`;

                // 显示页码（最多显示7个页码）
                const startPage = Math.max(1, pagination.current_page - 3);
                const endPage = Math.min(pagination.pages, pagination.current_page + 3);

                if (startPage > 1) {
                    paginationHtml += `<li class="page-item"><a class="page-link page-btn" href="#" data-page="1">1</a></li>`;
                    if (startPage > 2) {
                        paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
                    }
                }

                for (let i = startPage; i <= endPage; i++) {
                    paginationHtml += `
            <li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                <a class="page-link page-btn" href="#" data-page="${i}">${i}</a>
            </li>`;
                }

                if (endPage < pagination.pages) {
                    if (endPage < pagination.pages - 1) {
                        paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
                    }
                    paginationHtml += `<li class="page-item"><a class="page-link page-btn" href="#" data-page="${pagination.pages}">${pagination.pages}</a></li>`;
                }

                paginationHtml += `
            <li class="page-item ${pagination.has_next ? '' : 'disabled'}">
                <a class="page-link page-btn" href="#" data-page="${pagination.current_page + 1}">下一页</a>
            </li>`;
            }

            $('#paginationContainer').html(paginationHtml);
            $('#pageInfo').text(`共 ${pagination.total} 条记录，第 ${pagination.current_page} 页 / 共 ${pagination.pages} 页`);
        }
    </script>
</body>

</html>